package com.sqly.doc.menu.qianyue;

import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ihidea.multilinechooselib.MultiLineChooseLayout;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.sqly.doc.R;
import com.sqly.doc.adapter.CheckBoxAdapter;
import com.sqly.doc.adapter.CommonAdapter;
import com.sqly.doc.adapter.ViewHolder;
import com.sqly.doc.base.MyBaseActivity;
import com.sqly.doc.pojo.JuMin;
import com.sqly.doc.pojo.RetMsg;
import com.sqly.doc.pojo.ServicePackage;
import com.sqly.doc.pojo.SignUpContent;
import com.sqly.doc.pojo.SignUpNew;
import com.sqly.doc.pojo.TeamMember;
import com.sqly.doc.util.HttpUrl;
import com.sqly.doc.util.LvHeightUtil;
import com.sqly.doc.util.MyToastUtil;
import com.sqly.doc.util.NetWorkUtils;
import com.sqly.doc.util.SharedPreferencesUtils;
import com.sqly.doc.util.Url;
import com.sqly.doc.util.UserClient;
import com.sqly.doc.view.StringUtils;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import org.litepal.crud.DataSupport;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.Header;

//import cn.pedant.SweetAlert.SweetAlertDialog;


/**
 * Created by Administrator on 2017-12-05.
 */

public class qianyue_view extends MyBaseActivity {
    //标题
    TextView title, uname;
    /////////////////////////////////甲方内容////////////////////////////////
    TextView qyjg, qysj, fwtd, zgys;
    ListView listView,fwblistView;//团队列表
    EditText lxdh, jmlxdh, jmlxrdh;
    Spinner qynx;
    private List<String> qynxdata = new ArrayList<>();
    /////////////////////////////////////乙方内容////////////////////////////////
    TextView jmxm, jtzz;
    MultiLineChooseLayout fwb;//服务包内容
    private List<String> fwbdata = new ArrayList<>();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    List<TeamMember> memberListInTeam;//医疗团队成员
    JuMin juMin;
    Context con = qianyue_view.this;
    ZLoadingDialog dialog;
    ImageView brqm;
    String brqmpic = "";
    SignUpNew obj ;
    List<SignUpContent>  contents = new ArrayList<SignUpContent>();
    String teamid = "";
    List<ServicePackage> servicePackageList  = new ArrayList<ServicePackage>();//医疗团队成员
    TextView fwnrid, fwnrname;
    int pageNum1 = 1;// 无关键字页数

    @Override
    protected void initUI() {
        setContentView(R.layout.qianyue_view);
        init();
    }
    public void init(){
        juMin = (JuMin) getIntent().getExtras().getSerializable("juMin");
        brqm = (ImageView) findViewById(R.id.qm);
        dialog = new ZLoadingDialog(con);
        dialog.setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE)//设置类型
                .setLoadingColor(Color.parseColor("#1C86EE"))//颜色
                .setHintText("Loading...")
                .setHintTextSize(16) // 设置字体大小 dp
                .setHintTextColor(Color.parseColor("#1C86EE"));  // 设置字体颜色
//标题
        title = (TextView) findViewById(R.id.title);
        uname = (TextView) findViewById(R.id.uname);
        title.setText("已签约信息");
        uname.setText("");
        qyjg = (TextView) findViewById(R.id.qyjg);//签约机构
        qysj = (TextView) findViewById(R.id.qysj);//签约时间
        qysj.setText(df.format(new Date()));
        fwtd = (TextView) findViewById(R.id.fwtd);//服务团队
        zgys = (TextView) findViewById(R.id.zgys);//主管医生
        lxdh = (EditText) findViewById(R.id.lxdh);//联系电话
        jmlxdh = (EditText) findViewById(R.id.jmlxdh);//居民本人电话
        jmlxrdh = (EditText) findViewById(R.id.jmlxrdh);//居民联系人电话

        jmxm = (TextView) findViewById(R.id.jmxm);//居民姓名

        if (juMin != null && !StringUtils.isEmpty(juMin.getXINGMING()))
            jmxm.setText(juMin.getXINGMING());
        if (juMin != null && !StringUtils.isEmpty(juMin.getLXDH()))
            jmlxdh.setText(juMin.getLXDH());
        if (juMin != null && !StringUtils.isEmpty(juMin.getLXRDH()))
            jmlxrdh.setText(juMin.getLXRDH());

        jtzz = (TextView) findViewById(R.id.jtzz);
        if (juMin != null && !StringUtils.isEmpty(juMin.getCZDZ()))
            jtzz.setText(juMin.getCZDZ());

        qynx = (Spinner) findViewById(R.id.qynx);//签约年限
        fwb = (MultiLineChooseLayout) findViewById(R.id.fwnr);//服务内容
        listView = (ListView) findViewById(R.id.listView);
        fwblistView= (ListView) findViewById(R.id.fwblistView);
        fwnrid = (TextView) findViewById(R.id.fwnrid);
        fwnrname = (TextView) findViewById(R.id.fwnrname);

        if (!NetWorkUtils.isNetworkConnected(con)) {
            MyToastUtil.ShowToast(con, "联网失败");
        }else{
            RequestParams ps = new RequestParams();
            ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
            ps.add("type", "2");
            ps.add("party_b_id", juMin.getJKDAH());

            UserClient.get(HttpUrl.GetSignUpInfo, ps, new AsyncHttpResponseHandler() {
                @Override
                public void onStart() {
                    super.onStart();
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                    MyToastUtil.ShowToast(con, "请求失败");
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                    String content = new String(response);
                    RetMsg ret = JSON.parseObject(content, RetMsg.class);
                    if (ret.getCode().equals("200")) {
                        obj = JSON.parseObject(ret.getRd(), SignUpNew.class);
                        teamid = obj.getParty_a_team_id();
                        qysj.setText(obj.getTbtime());
                        fwtd.setText(obj.getParty_a_team_name());
                        zgys.setText(obj.getParty_a_contractor_name());
                        lxdh.setText(obj.getParty_a_tel());
                        brqmpic = obj.getImg();
                        if(null != obj.getImg()){
                            ImageLoader.getInstance().displayImage(Url.img_url() + obj.getImg(), brqm);
                        }
                        Map<String, Object> map = JSON.parseObject(ret.getOtherParams(), Map.class);
                        List<Map<String, Object>> listMap =  (List<Map<String, Object>>)map.get("contents");

                        //填充我的团队信息
                        qyjg.setText(obj.getNameD());
                        fwtd.setText(obj.getParty_a_team_name());
                        ///签约年限
                        qynxdata.add("1");
//                        qynxdata.add("2");
//                        qynxdata.add("3");
                        qynx.setAdapter(new CommonAdapter<String>(con, qynxdata, R.layout.sp_item) {
                            @Override
                            public void convert(ViewHolder helper, String item) {
                                helper.setText(R.id.name, item);
                            }
                        });
                        if (obj!=null && !StringUtils.isEmpty(obj.getContract_age())) {
                            qynx.setSelection(Integer.parseInt(obj.getContract_age())-1);
                        }
                    } else {
                        MyToastUtil.ShowToast(con, "获取错误");
                    }
                }

            });
            //团队成员
            getSignUpMemberByTeam(juMin.getSignupid());
            getServicePack(juMin.getSignupid());
        }
    }

    /**
     * 根据 teamId 查询团队成员列表数据
     * @param signupid
     */
    private void getSignUpMemberByTeam(String signupid){
        //团队成员
        RequestParams ps = new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
        ps.add("type", "2");
        ps.add("page", "1");
        ps.add("pageSize","100");
        ps.add("signupid", signupid);
        UserClient.get(HttpUrl.GetSignUpMemberInTeam, ps, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                MyToastUtil.ShowToast(con, "请求失败");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                String content = new String(response);
                dialog.dismiss();
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {
                    if (pageNum1 == 1)
                        memberListInTeam = new ArrayList<TeamMember>();
                    List<TeamMember> tempList = JSON.parseArray(ret.getRd(), TeamMember.class);
                    for (int i = 0; i < tempList.size(); i++) {
                        memberListInTeam.add(tempList.get(i));
                    }
                    listView.setAdapter(new CommonAdapter<TeamMember>(con, memberListInTeam, R.layout.qy_team_item) {
                        @Override
                        public void convert(ViewHolder helper, TeamMember item) {
                            helper.setText(R.id.name, item.getMember_name());
                            helper.setText(R.id.tdmc, item.getName());
                            helper.setText(R.id.jgmc, item.getNameD());
                        }
                    });
                    LvHeightUtil.setListViewHeightBasedOnChildren(listView);
                }
            }
        });
    }

    /***
     * 查询服务包数据
     */
    private void getServicePack(String signupId){
        RequestParams ps = new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
        ps.add("type", "2");
        ps.add("page",  "1");
        ps.add("signupid", signupId);
        ps.add("pageSize","100");
        UserClient.get(HttpUrl.GetSpBySingupIdPagelst, ps, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                MyToastUtil.ShowToast(con, "请求失败");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                String content = new String(response);
                dialog.dismiss();
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {
                    List<ServicePackage> tempList = JSON.parseArray(ret.getList(), ServicePackage.class);
                    JSONArray jsArr = JSON.parseArray(ret.getList());
                    for (int i = 0; i < jsArr.size(); i++) {
                        JSONObject j = jsArr.getJSONObject(i);
                        tempList.get(i).setSid(j.getString("id"));
                        tempList.get(i).setChecked(true);
                    }
                    for (int i = 0; i < tempList.size(); i++) {
                        fwbdata.add(tempList.get(i).getName());
                    }
                    fwb.setList(fwbdata);

                    String fwnrids = "",fwnrnames = "";
                    for (int i = 0; i < tempList.size(); i++) {
                        ServicePackage temp = (ServicePackage)tempList.get(i);
                        servicePackageList.add(temp);
                        fwnrids = temp.getSid()+","+fwnrids;
                        fwnrnames =  temp.getName()+","+fwnrnames;
                    }
                    if(null != fwnrids && fwnrids.length()>1 && fwnrids.endsWith(",")){
                        fwnrids = fwnrids.substring(0, fwnrids.length()-1);
                    }
                    if(null != fwnrnames && fwnrnames.length()>1 && fwnrnames.endsWith(",")){
                        fwnrnames = fwnrnames.substring(0, fwnrnames.length()-1);
                    }

                    final Map<String, String> mapTemp = new HashMap<String, String>();
                    final CheckBoxAdapter myAdapter = new CheckBoxAdapter(con);
                    myAdapter.setDatas(servicePackageList);
                    fwblistView.setAdapter(myAdapter);
                    LvHeightUtil.setListViewHeightBasedOnChildren(fwblistView);

                    fwnrid.setText(fwnrids);
                    fwnrname.setText(fwnrnames);
                }
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {

    }
}
